import { NextRequest, NextResponse } from 'next/server';
import fs from 'fs/promises';
import path from 'path';

// 权限验证函数
function checkPermission(request: NextRequest): { hasPermission: boolean; error?: string } {
    const referer = request.headers.get('referer');
    if (!referer) {
        return { hasPermission: false, error: '缺少来源页面信息' };
    }

    try {
        const url = new URL(referer);
        const pathname = url.pathname;

        // 只允许从management页面访问
        if (pathname !== '/management') {
            return { hasPermission: false, error: '权限不足，仅允许从管理页面访问' };
        }

        return { hasPermission: true };
    } catch (error) {
        return { hasPermission: false, error: '无效的来源页面信息' };
    }
}

export async function POST(request: NextRequest) {
    try {
        // 权限检查
        const permissionCheck = checkPermission(request);
        if (!permissionCheck.hasPermission) {
            return NextResponse.json(
                { success: false, error: permissionCheck.error },
                { status: 403 }
            );
        }

        const { sourcePath, targetPath, type } = await request.json();

        if (!sourcePath || !targetPath) {
            return NextResponse.json(
                { success: false, error: '源路径和目标路径都是必需的' },
                { status: 400 }
            );
        }

        const baseDir = path.join(process.cwd(), 'storage');
        const sourceFullPath = path.join(baseDir, sourcePath);
        const targetFullPath = path.join(baseDir, targetPath);

        const normalizedSourcePath = path.normalize(sourceFullPath);
        const normalizedTargetPath = path.normalize(targetFullPath);
        const normalizedBaseDir = path.normalize(baseDir);

        if (!normalizedSourcePath.startsWith(normalizedBaseDir) ||
            !normalizedTargetPath.startsWith(normalizedBaseDir)) {
            return NextResponse.json(
                { success: false, error: '无效的路径' },
                { status: 400 }
            );
        }

        try {
            const sourceStats = await fs.stat(sourceFullPath);

            // 检查目标路径是否已存在
            try {
                await fs.access(targetFullPath);
                return NextResponse.json(
                    { success: false, error: '目标路径已存在' },
                    { status: 409 }
                );
            } catch {
                // 目标路径不存在，可以继续
            }

            // 确保目标目录存在
            const targetDir = path.dirname(targetFullPath);
            await fs.mkdir(targetDir, { recursive: true });

            if (type === 'directory') {
                if (!sourceStats.isDirectory()) {
                    return NextResponse.json(
                        { success: false, error: '源路径不是文件夹' },
                        { status: 400 }
                    );
                }
                await fs.rename(sourceFullPath, targetFullPath);
            } else {
                if (!sourceStats.isFile()) {
                    return NextResponse.json(
                        { success: false, error: '源路径不是文件' },
                        { status: 400 }
                    );
                }
                await fs.rename(sourceFullPath, targetFullPath);
            }

            return NextResponse.json({ success: true });
        } catch (error) {
            if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
                return NextResponse.json(
                    { success: false, error: '源文件或文件夹不存在' },
                    { status: 404 }
                );
            }
            throw error;
        }
    } catch (error) {
        console.error('Error moving file:', error);
        return NextResponse.json(
            { success: false, error: '移动文件失败' },
            { status: 500 }
        );
    }
} 